package nl.justobjects.pushlet.pushmanager;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

public class PushUtils {
	
	public static Map<String, Object> getPushParams(HttpServletRequest request) {
		return getPushParams(request, null);
	}
	
	public static void setPushData(Map<String, Object> params, Map<String, String> map) {
		params.put("data", map);
	}
	
	public static void setUnicastPIDs(Map<String, Object> params, List<String> pids) {
		params.put("pids", pids);
	}
	
	/**
	 * 打包需要推送的数据和参数
	 * @param request
	 * @param dataKeys
	 * @return
	 */
	public static Map<String, Object> getPushParams(HttpServletRequest request, String[] dataKeys) {
		String subject = request.getParameter("subject");
		String label = request.getParameter("label");
		String pid = request.getParameter("pid");
		String pids = request.getParameter("pids");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("subject", subject);
		if (pid != null)
			params.put("pid", pid);
		if (label != null)
			params.put("label", label);
		if (pids != null) {
			params.put("pids", pids.split(","));
		}
		if (dataKeys != null && dataKeys.length > 0) {
			Map<String, String> map = new HashMap<String, String>();
			for (int i = 0, len = dataKeys.length; i < len; i++) {
				String value = request.getParameter(dataKeys[i]);
				if (StringUtils.isNotBlank(value))
					map.put(dataKeys[i], value);
			}
			params.put("data", map);
		}
		return params;
	}
	
	public static Map<String, Object> toMap(Object obj, String[] fileds) {
		Map<String, Object> map = new HashMap<String, Object>();
		Set<String> requiredFileds = new HashSet<String>();
		CollectionUtils.addAll(requiredFileds, fileds);
		Class<? extends Object> clazz = obj.getClass();
		Field[] fs = clazz.getDeclaredFields();
		for (int i = 0, len = fs.length; i < len; i++) {
			Field field = fs[i];
			field.setAccessible(true);
			try {
				Object val = field.get(obj);
				String name = field.getName();
				if (requiredFileds.contains(name) && val != null)
					map.put(name, val);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return map;
	}
}
